package com.mall.b2c.service.impl;

import com.mall.b2c.dao.StoreGoodsDao;
import com.mall.b2c.domain.goods.GoodsDomain;
import com.mall.b2c.domain.store.StoreDomain;
import com.mall.b2c.domain.store.StoreGoodsDomain;
import com.mall.b2c.service.GoodsService;
import com.mall.b2c.service.StoreGoodsService;
import com.mall.b2c.service.StoreService;
import com.mall.common.bean.Message;
import com.mall.common.hibernate.Finder;
import com.mall.common.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Misun on 2016/12/28.
 * 门店-商品关联类
 */
@Service
@Transactional(readOnly = true)
public class StoreGoodsServiceImpl extends BaseServiceImpl<StoreGoodsDomain, Long> implements StoreGoodsService {
    @Resource
    public void setBaseDao(StoreGoodsDao storeGoodsDao) {
        super.setBaseDao(storeGoodsDao);
    }


    @Resource private GoodsService goodsService;
    @Resource private StoreService storeService;

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public Message addGoods(Long[] goodsIds, Long storeId) {
        List<GoodsDomain> list =  goodsService.get(goodsIds);
        StoreDomain store = storeService.find(storeId);
        if(store  == null){
            return Message.error("门店不存在",null);
        }
        for(GoodsDomain goods : list){
            Finder finder = Finder.create("select count(bean) from StoreGoodsDomain bean where goods.id = :goodsId and store.id=:storeId");
            finder.setParam("goodsId", goods.getId());
            finder.setParam("storeId", store.getId());
            if(Long.valueOf(String.valueOf(finder.findUniqueByHQL())) > 0){
                return Message.error("商品【"+goods.getName()+"】已关联",null);
            }
            StoreGoodsDomain storeGoods = new StoreGoodsDomain();
            storeGoods.setGoods(goods);
            storeGoods.setStore(store);
            storeGoods.setIsMarketable(false);
            this.persist(storeGoods);
        }
        return Message.success("关联成功",null);
    }
}
